﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm;
using Xrm;
using Microsoft.Xrm.Sdk.Client;
using System.Configuration;

namespace BulkDelete
{
    class Program
    {
        static void Main(string[] args)
        {
            var xrm = new XrmServiceContext("Xrm");
            DateTime start = DateTime.Now;

            string[] entityNames = new string[] { "resco_mobiletracking", "resco_mobilesecuritypolicy", "resco_mobileproject", "resco_mobilelicense", "resco_mobiledevice", "resco_mobiledata", "email", "f1_workorderstatus", "f1_workorderskill", "f1_workorderservicetask", "f1_workorderservice", "f1_workorderschedulestatus", "f1_workorderschedulejournal", "f1_workorderschedulechange", "f1_workorderproduct", "f1_poreceiptproduct", "f1_poreceipt", "f1_workorder", "f1_workorderincident", "annotation", "f1_uniquenumber", "f1_timeoffreason", "f1_timeoffentity", "f1_taxcodedetail", "f1_taxcode", "f1_systemuserschedulersettings", "f1_smsactivity", "f1_skilltype", "f1_shipvia", "f1_servicetasktype", "f1_servicelevel", "f1_schedulingrule", "f1_scheduletimestamp", "f1_scheduleboardsettings", "f1_rtvtype", "f1_rtvsubstatus", "f1_rtvproductreason", "f1_rtvproduct", "f1_rtv", "f1_routingoptimizationrequest", "f1_rmatype", "f1_rmasubstatus", "f1_rmareceiptproduct", "f1_rmareceipt", "f1_rmaproductreason", "f1_rmaproduct", "f1_rma", "f1_resourceterritory", "f1_resourceskill", "f1_resourcepaytype", "f1_resourcegroupmember", "f1_inventoryjournal", "f1_resourcecategory", "f1_productinventory", "f1_priority", "f1_posubstatus", "f1_portalrole", "f1_purchaseorderproduct", "f1_poolwogeneration", "f1_purchaseorder", "f1_pobill", "f1_paymentterm", "f1_paymentmethod", "f1_paymentdetails", "f1_payment", "f1_ivractivity", "f1_inventoryadjstproduct", "f1_inventorytransfer", "f1_workorderresource", "f1_incidenttype", "f1_incidentskill", "f1_incidentservicetask", "f1_incidentservice", "f1_incidentproduct", "f1_glaccount", "f1_fieldonesystemjob", "f1_fieldonesetting", "f1_fieldonepricelistitem", "f1_customerequipment", "f1_agreementsubstatus", "f1_agreementservicetask", "f1_agreementservice", "f1_agreementschedulesetup", "f1_agreementscheduledate", "f1_agreementproduct", "f1_agreementinvoicesetup", "f1_agreementinvoiceproduct", "f1_agreementinvoicedate", "f1_agreementincident", "f1_agreement", "account", "product", "contact", "f1_zipcode", "f1_potype", "f1_inventoryadjustment", "f1_warehouse", "f1_workordertype" };
            string[] entityKeyFieldNames = new string[entityNames.Length];

            entityKeyFieldNames[6] = "activityid";  //deleteRecords("email", xrm, "activityid");
            entityKeyFieldNames[26] = "activityid";  //deleteRecords("f1_smsactivity", xrm, "activityid");
            entityKeyFieldNames[65] = "activityid";  //deleteRecords("f1_ivractivity", xrm, "activityid");

            for (int i = 0; i < entityNames.Length; i++)
            {
                DateTime s = DateTime.Now;
                Console.WriteLine("Starting entity: " + entityNames[i] + " ( " + (i + 1).ToString() + " of " + entityNames.Length.ToString() + ") Start: " + s.ToShortTimeString());

                deleteRecords(entityNames[i], xrm, entityKeyFieldNames[i]);

                DateTime e = DateTime.Now;
                TimeSpan d = e - s;
                Console.WriteLine("Finished entity: " + entityNames[i] + " Duration: " + (int)d.TotalMinutes + ":" + (int)d.TotalSeconds);
            }

            DateTime end = DateTime.Now;
            TimeSpan dif = end - start;
            Console.WriteLine("Press any key to exit. Timespent: " + (int)dif.TotalMinutes + ":" + (int)dif.TotalSeconds);
            Console.ReadKey();
        }

        private static void deleteRecords(string entityname, XrmServiceContext xrm, string keyFieldName = "")
        {
            Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression();
            query.EntityName = entityname;

            keyFieldName = String.IsNullOrEmpty(keyFieldName) ? entityname + "id" : keyFieldName;
            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(keyFieldName);

            int count = 0;
            do
            {
                try
                {
                    EntityCollection entity = xrm.RetrieveMultiple(query);
                    count = entity.Entities.Count;
                    if (entity.Entities.Count > 0)
                    {
                        for (int i = 0; i < entity.Entities.Count; i++)
                        {
                            try
                            {
                                Entity et = entity.Entities[i];
                                xrm.Delete(et.LogicalName, et.Id);
                                Console.WriteLine("Record " + i.ToString() + " of " + entity.Entities.Count.ToString() + " " + et.LogicalName + " " + et.Id.ToString());
                            }
                            catch (Exception ex)
                            {
                                continue;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    int i;
                }
            }
            while (count == 5000);
        }
    }
}


